package com.cn.example.rpc;

import com.cn.example.rpc.impl.DemoService;
import com.cn.msg.ProxyMessage;
import com.cn.util.GsonUtil;
import com.cn.util.SerializationUtil;
import org.apache.commons.lang3.time.DateUtils;
import sun.java2d.pipe.SpanIterator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static Map<String, Object> map = new HashMap<>();

    public static void put(Object obj) {
        //对象是否继承了接口
        Class<?>[] interfaces = obj.getClass().getInterfaces();
        for (Class<?> o : interfaces) {
            map.put(o.getName(), obj);
        }

    }

    public static Object get(String name) {
        return map.get(name);
    }

    public static <T> T getProxy(final Class<T> c) {
        return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class[]{c}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName());
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.setArgs(args);//参数
                proxyMessage.setName(c.getName());
                proxyMessage.setParamterTypes(method.getParameterTypes());
                String uid = String.format("%s_%d", c.getName(), new Date().getTime());
                proxyMessage.setId(uid);

                byte[] bytes = SerializationUtil.serializeToByte(proxyMessage);
                ProxyMessage proxyMessage1 = SerializationUtil.deserializeFromByte(bytes, ProxyMessage.class);
                if (proxyMessage1 != null) {
                    System.out.println(proxyMessage1.getName());
                }
                return null;
            }
        });
    }

    public static void main(String[] args) {
        IDemoService demoService = new DemoService();
//        put(demoService);
        System.out.println(IDemoService.class.getName());
//        IDemoService demoService = getProxy(IDemoService.class);
//        demoService.sayHello("cn_yaojin", 2, 14d, BigDecimal.ZERO);

    }

}
